import svg2img from 'svg2img';
import sharp from 'sharp';
import fs from 'fs';
import { tmpNameSync } from 'tmp';
import { logger, saveBufferToLocal } from './src/tools/index.js';

const buffer = await convertSvg2ImgBuffer(`<svg viewBox="0 0 400 600" xmlns="http://www.w3.org/2000/svg">
  <rect width="100%" height="100%" fill="#f0e8d9"/>
  <g transform="translate(20, 20)">
    <text x="180" y="40" font-family="楷体" font-size="24" fill="#4a4a4a" text-anchor="middle">汉语新解</text>
    <line x1="20" y1="60" x2="340" y2="60" stroke="#4a4a4a" stroke-width="1"/>
    <text x="20" y="100" font-family="楷体" font-size="18" fill="#4a4a4a">打工人</text>
    <text x="20" y="130" font-family="Arial" font-size="16" fill="#4a4a4a">Worker</text>
    <text x="20" y="160" font-family="Malgun Gothic" font-size="16" fill="#4a4a4a">일하는 사람</text>
    <text x="20" y="220" font-family="楷体" font-size="16" fill="#4a4a4a" width="340">
      <tspan x="20" dy="0">现代社会的奴隶契约签署者，</tspan>
      <tspan x="20" dy="24">用青春和理想换取房贷和车位的赛博朋克。</tspan>
      <tspan x="20" dy="24">他们是资本主义游戏里的NPC，</tspan>
      <tspan x="20" dy="24">每天重复着相同的对话和动作，</tspan>
      <tspan x="20" dy="24">直到电量耗尽，游戏结束。</tspan>
    </text>
    <g transform="translate(170, 400)">
      <circle cx="0" cy="0" r="50" fill="none" stroke="#4a4a4a" stroke-width="2"/>
      <line x1="-30" y1="0" x2="30" y2="0" stroke="#4a4a4a" stroke-width="2"/>
      <line x1="0" y1="-30" x2="0" y2="30" stroke="#4a4a4a" stroke-width="2"/>
      <path d="M-20,-20 L20,20 M-20,20 L20,-20" stroke="#4a4a4a" stroke-width="2" fill="none"/>
    </g>
  </g>
</svg>`);

const filePath = await saveBufferToLocal("test.png", buffer);

async function convertSvg2ImgBuffer(svgString) {
    return new Promise((resolve, reject) => {
        // 创建一个临时SVG文件
        const tmpFile = tmpNameSync({ postfix: '.svg' });
        fs.writeFileSync(tmpFile, svgString);

        // 使用sharp转换SVG为PNG
        sharp(tmpFile)
            .resize({ width: 800, height: 600, fit: 'outside' })
            .png({
                quality: 100,
                compressionLevel: 0,
            }) // 设置PNG质量为100
            .toBuffer()
            .then(buffer => {
                // 成功获取Buffer，删除临时文件
                fs.unlinkSync(tmpFile);
                resolve(buffer);
            })
            .catch(err => {
                // 出错时删除临时文件
                fs.unlinkSync(tmpFile);
                reject(err);
            });
    })
};